import { getContentsGet } from '@/services/codeTrail/cangku';
import {
  BranchesOutlined,
  DeleteOutlined,
  EditOutlined,
  FileOutlined,
  FolderFilled,
  FolderOutlined,
  LeftOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import styles from './index.module.less';
interface Props {
  unfold?: () => void;
  data: {
    human_name?: string;
    full_name?: string;
    html_url?: string;
  };
}
interface Content {
  name: string;
  type: 'dir' | 'file';
  path: string;
  content?: string;
  sha: string;
}

const RepositoryBox: React.FC<Props> = ({ data }) => {
  const [isFolded, setFolded] = useState<'fold' | 'unfold'>('fold'); //展开状态ssss
  const [repoContents, setRepoContents] = useState<Content[]>([]); //请求响应内容
  const [currentPath, setCurrentPath] = useState<string>(''); //当前路径
  const [pathHistory, setPathHistory] = useState<string[]>([]); // 新增状态，用于跟踪路径历史
  const [dataType, setDataType] = useState<string>('dir');
  const [isMenuOpen, setIsMenuOpen] = useState<boolean>(false);

  // 从full_name中提取owner和repo
  const [owner, repo] = data.full_name?.split('/') || [];

  useEffect(() => {
    if (isFolded === 'unfold' && owner && repo) {
      fetchRepoContents(owner, repo, currentPath);
    }
  }, [isFolded]);
  const handleMenuOpen= (e) => {
    e.stopPropagation();
    setIsMenuOpen(!isMenuOpen);
  };

  const fetchRepoContents = async (
    owner: string,
    repo: string,
    path: string,
    updateHistory: boolean = true,
  ) => {
    
    const response = await getContentsGet({ owner, repo, path, ref: 'master' });
    if (response && response.data) {
      setRepoContents(response.data);
      setCurrentPath(path); // 更新当前路径
      setPathHistory((prevHistory) => {
        // 只有当路径不是历史记录的最后一个条目时，才添加到历史记录中
        if (prevHistory.length === 0 || prevHistory[prevHistory.length - 1] !== path) {
          return [...prevHistory, path];
        }
        return prevHistory; // 否则，返回原历史记录
      });
    }
  };

  const handleItemClick = (path: string, type: string) => {
    fetchRepoContents(owner!, repo!, path);
    setDataType(type);
  };

  const goBack = () => {
    if (pathHistory.length > 0) {
      const newPathHistory = [...pathHistory];
      newPathHistory.pop(); // 移除当前路径
      const prevPath = newPathHistory[newPathHistory.length - 1] || '';
      fetchRepoContents(owner!, repo!, prevPath, false); // 获取上一级路径的内容
      setPathHistory(newPathHistory); // 更新路径历史
      setDataType('dir');
    }
  };

  return (
    <div className={styles.boxComponents}>
      <div
        className={styles.infoBox}
        onClick={() => setFolded(isFolded === 'unfold' ? 'fold' : 'unfold')}
      >
        <div className={styles.name}>{data.full_name}</div>
        <div className={styles.btn}>
          {isMenuOpen&&
          <div className={[styles.menu].join(" ")} onClick={(e)=>{e.stopPropagation();}}>
            <div ><DeleteOutlined/></div>
            <div ><EditOutlined /></div>
          </div>  
          }
          <MoreOutlined
            rotate={isMenuOpen?0:90}
            style={{ fontSize: '28px', color: '#3D3D3D' }}
            className={styles.icon}
            //菜单
            onClick={(e) => {
              handleMenuOpen(e);
            }}
          />
          
          
        </div>
      </div>
      {isFolded === 'unfold' && (
        <div className={styles.unfoldArea}>
          <div className={styles.tab}>
            <div className={styles.path}>Path: {currentPath || 'root'}</div>
            <div className={styles.branch}>
              <BranchesOutlined />
              master
            </div>
          </div>
          <table className={styles.table}>
            <thead>
              <tr>{dataType === 'file' ? <th>{currentPath?.split('/').pop()}</th> : null}</tr>
            </thead>
            <tbody>
              {currentPath ? (
                <tr>
                  <div onClick={goBack}>
                    <LeftOutlined />
                    <FolderFilled />
                  </div>
                </tr>
              ) : null}
              {repoContents.map((data) => (
                <tr key={data.sha}>
                  {dataType === 'file' ? (
                    <td className={styles.fileContent}>
                      <div className={styles.txt}>{data.content}</div>
                    </td>
                  ) : (
                    <td onClick={() => handleItemClick(data.path, data.type)}>
                      {data.type === 'file' ? <FileOutlined /> : <FolderOutlined />} {data.name}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default RepositoryBox;
